package many_thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyLock implements Runnable {
    private int ticket = 10;
    private final Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (this.sale());
    }

    private boolean sale() {
        lock.lock();
        try {
            if (ticket < 0) {
                System.out.println(Thread.currentThread().getName() + "的票已经售完，当前剩余票数为：" + ticket);
                return false;
            }
            Thread.sleep(200);
            System.out.println(Thread.currentThread().getName() + "正在售票，此时的票数为：" + --ticket);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return true;
    }
}
